# -*- coding:utf-8 -*-
# anaconda python 3.8.5
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np


def addTrace(
    cat,
    df,
    colour,
    fill=None,
    mode="lines",
    text="",
    yaxis="y",
    dash="solid",
    showlegend=True,
    linewidth=2,
    markersize=3,
):
    Temp = go.Scatter(
        x=df["date"],
        y=round(df[cat], 5),
        marker=dict(color=colour, size=markersize),
        name=cat,
        #   text=df['date'],
        mode=mode,  # ['none', 'tozeroy', 'tozerox', 'tonexty', 'tonextx', 'toself', 'tonext']
        fill=fill,
        text=text,
        line=dict(width=linewidth, dash=dash),
        yaxis=yaxis,
        showlegend=showlegend,
    )
    return Temp


def MainMaTraceAdd(cols, fig, stockdata, Colours):
    y2, y1, y4 = 0, 0, 0

    for col in cols:
        if ("_by%" in col and "sum" in col and "All" in col) or "sort" in col:
            if "All" in col and "sort" in col:
                if "T" in col:
                    fig.add_trace(
                        addTrace(
                            col, stockdata, Colours[y2], yaxis="y3", showlegend=False
                        )
                    )
                else:
                    fig.add_trace(
                        addTrace(
                            col,
                            stockdata,
                            Colours[y2],
                            yaxis="y3",
                            dash="dot",
                            showlegend=False,
                        )
                    )
                y2 += 1
            elif "All" in col and "sum" in col:
                if "T" in col:
                    fig.add_trace(
                        addTrace(
                            col,
                            stockdata,
                            Colours[y4],
                            yaxis="y4",
                            dash="dot",
                            showlegend=False,
                        )
                    )
                else:
                    fig.add_trace(
                        addTrace(
                            col, stockdata, Colours[y4], yaxis="y4", showlegend=False
                        )
                    )
                y4 += 1

        elif "ma" in col and ("Boll" and "by%") not in col and "-" not in col:
            stockdata[col].replace(0, np.nan, inplace=True)
            fig.add_trace(
                addTrace(
                    col,
                    stockdata,
                    Colours[y1],
                    dash="dot",
                    yaxis="y1",
                    showlegend=False,
                )
            )
            y1 += 1

    return fig


def Main_Candlestick_plot(df, save_info=[]):
    cols = df.columns.tolist()
    CSS_Colours = [
        "yellowgreen",
        "tomato",
        "lightskyblue",
        "lightpink",
        "Aquamarine",
        #    'aliceblue',
        #    'mistyrose',
        "pink",
        "limegreen",
        #    'skyblue',
        "hotpink",
        "cyan",
        "gold",
        "lightsalmon",
        "green",
        "orange",
        "deeppink",
        "Cyan",
        "aqua",
        "aquamarine",
        "azure",
        "beige",
        "bisque",
        "blanchedalmond",
        "blueviolet",
        "burlywood",
        "cadetblue",
        "chartreuse",
        "chocolate",
        "coral",
        # "cornflowerblue",
        # "cornsilk",
        # "crimson",
        # "darkblue",
        # "darkcyan",
        # "darkgoldenrod",
        # "darkgray",
        # "darkgrey",
        # "darkgreen",
        # "darkkhaki",
        # "darkmagenta",
        # "darkolivegreen",
        # "darkorange",
        #    'darkorchid', 'darkred', 'darksalmon', 'darkseagreen',
        #    'darkslateblue', 'darkslategray', 'darkslategrey',
        #    'darkturquoise', 'darkviolet',  'deepskyblue',
        #    'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
        #    'forestgreen', 'fuchsia', 'gainsboro','goldenrod',  'grey',
        #    'greenyellow', 'honeydew',  'indianred', 'indigo',
        #    'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
        #    'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
        #    'lightgoldenrodyellow', 'lightgray', 'lightgrey',
        #    'lightgreen', 'lightpink',  'lightseagreen',
        #    'lightslategray', 'lightslategrey',
        #    'lightsteelblue', 'lightyellow', 'lime', 'limegreen',
        #    'linen', 'magenta', 'maroon', 'mediumaquamarine',
        #    'mediumblue', 'mediumorchid', 'mediumpurple',
        #    'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
        #    'mediumturquoise', 'mediumvioletred', 'midnightblue',
        #    'mintcream',  'moccasin', 'navajowhite', 'navy',
        #    'oldlace', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise',
        #    'palevioletred', 'papayawhip', 'peachpuff', 'peru',
        #    'plum', 'powderblue', 'purple', 'red', 'rosybrown',
        #    'royalblue', 'rebeccapurple', 'saddlebrown', 'salmon',
        #    'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver',
        #    'slategray', 'slategrey', 'snow','springgreen',  'tan', 'teal', 'thistle',
        #    'turquoise', 'violet', 'wheat','yellow',
    ]
    fig = go.Figure()
    TempCol = {
        "Y_prodict_compare": {
            "mode": "lines",
            "name": "predict_compare",
            "text": "prodict_date_compare",
            "dash": "dot",
            "color": "OliveDrab",
            "yaxis": "y1",
            "showlegend": True,
        },
        "polynomial_X_3_compare": {
            "mode": "lines",
            "name": "X_compare",
            "text": "prodict_date_compare",
            "dash": "dot",
            "color": "OliveDrab",
            "yaxis": "y1",
            "showlegend": True,
        },
        "polynomial_X_2_compare": {
            "mode": "lines",
            "name": "X^2_compare",
            "text": "prodict_date_compare",
            "dash": "dot",
            "color": "OliveDrab",
            "yaxis": "y2",
            "showlegend": False,
        },
        "polynomial_X_1_compare": {
            "mode": "lines",
            "name": "X^3_compare",
            "text": "prodict_date_compare",
            "dash": "dot",
            "color": "OliveDrab",
            "yaxis": "y2",
            "showlegend": False,
        },
        "Q_0_compare": {
            "mode": "lines",
            "name": "Q^3_compare",
            "text": "prodict_date_compare",
            "dash": "dot",
            "color": "OliveDrab",
            "yaxis": "y2",
            "showlegend": False,
        },
        "Q_1_compare": {
            "mode": "lines",
            "name": "Q^2_compare",
            "text": "prodict_date_compare",
            "dash": "dot",
            "color": "OliveDrab",
            "yaxis": "y2",
            "showlegend": False,
        },
        "Q_2_compare": {
            "mode": "lines",
            "name": "Q_compare",
            "text": "prodict_date_compare",
            "dash": "dot",
            "color": "OliveDrab",
            "yaxis": "y2",
            "showlegend": False,
        },
        "Y_prodict": {
            "mode": "lines",
            "name": "predict",
            "text": "prodict_date",
            "dash": "dot",
            "color": "SlateGray",
            "yaxis": "y1",
            "showlegend": True,
        },
        "polynomial_X_3": {
            "mode": "lines",
            "name": "X",
            "text": "prodict_date",
            "dash": "dot",
            "color": "LightSlateGray",
            "yaxis": "y1",
            "showlegend": True,
        },
        "polynomial_X_2": {
            "mode": "lines",
            "name": "X^2",
            "text": "prodict_date",
            "dash": "dot",
            "color": "LightSlateGray",
            "yaxis": "y2",
            "showlegend": False,
        },
        "polynomial_X_1": {
            "mode": "lines",
            "name": "X^3",
            "text": "prodict_date",
            "dash": "dot",
            "color": "LightSlateGray",
            "yaxis": "y2",
            "showlegend": False,
        },
        "Q_0": {
            "mode": "lines",
            "name": "Q^3",
            "text": "prodict_date",
            "dash": "dot",
            "color": "LightSteelBlue",
            "yaxis": "y2",
            "showlegend": False,
        },
        "Q_1": {
            "mode": "lines",
            "name": "Q^2",
            "text": "prodict_date",
            "dash": "dot",
            "color": "LightSteelBlue",
            "yaxis": "y2",
            "showlegend": False,
        },
        "Q_2": {
            "mode": "lines",
            "name": "Q",
            "text": "prodict_date",
            "dash": "dot",
            "color": "LightSteelBlue",
            "yaxis": "y2",
            "showlegend": False,
        },
    }
    for col in TempCol:
        if col in cols:
            ColDic = TempCol[col]
            fig.add_trace(
                go.Scatter(
                    x=df["date"],
                    y=df[col],
                    mode=ColDic["mode"],
                    name=ColDic["name"],
                    text=df[ColDic["text"]],
                    line=dict(width=2, dash=ColDic["dash"], color=ColDic["color"]),
                    yaxis=ColDic["yaxis"],
                    showlegend=ColDic["showlegend"],
                )
            )
    if "high" in cols:
        fig.add_trace(
            go.Candlestick(
                x=df["date"],
                open=df["open"],
                high=df["high"],
                low=df["low"],
                close=df["close"],
                text=df["date"],
                name="Candle",
                increasing_line_color="tomato",
                decreasing_line_color="yellowgreen",
                yaxis="y1",
            )
        )

    fig = MainMaTraceAdd(cols, fig, df, CSS_Colours)
    fig.add_trace(addTrace("Avg", df, "tomato", dash="dot", yaxis="y1"))

    TempCol = {
        "xss_0": {
            "y": "ys_0",
            "name": "root0",
            "color": "CornflowerBlue",
            "mode": "markers",
            "text": "date",
        },
        "xss_1": {
            "y": "ys_1",
            "name": "root1",
            "color": "LightSteelBlue",
            "mode": "markers",
            "text": "date",
        },
    }
    for col in TempCol:
        if col in cols:
            ColDic = TempCol[col]
            fig.add_trace(
                go.Scatter(
                    x=df[col],
                    y=df[ColDic["y"]],
                    mode=ColDic["mode"],
                    name=ColDic["name"],
                    text=df[ColDic["text"]],
                    marker=dict(color=ColDic["color"], size=10),
                    yaxis="y1",
                )
            )

    TempCol = {"volume": "pink", "amount": "tomato"}
    for col in TempCol:
        if col in cols:
            fig.add_trace(
                addTrace(
                    col,
                    df,
                    TempCol[col],
                    dash="dot",
                    fill="tozeroy",
                    showlegend=False,
                    yaxis="y5",
                )
            )

    TempCol = ["determination", "determination_X", "determination_compare"]
    for col in TempCol:
        if col in cols:
            fig.add_trace(
                go.Scatter(
                    x=df["date"],
                    y=df[col],
                    name=col,
                    text=df["date"],
                    marker=dict(color="tomato", size=10),
                    yaxis="y2",
                )
            )

    # fig.add_trace(addTrace("determination", df, "tomato", yaxis="y2", showlegend=False))

    # fig.add_trace(
    #     go.Scatter(
    #         x=df["date"],
    #         y=df["Y_prodict"],
    #         mode="lines",
    #         name="predict",
    #         text=df["prodict_date"],
    #         line=dict(width=2, dash="dot", color="gray"),
    #         yaxis="y1",
    #     )
    # )

    TempCol = {
        "MARKER=B": "tomato",
        "MARKER=S": "yellowgreen",
    }
    for col in TempCol:
        if col in cols:
            fig.add_trace(
                go.Scatter(
                    x=df["date"],
                    y=df[col],
                    marker=dict(color=TempCol[col], size=10),
                    name=col,
                    mode="markers",
                    yaxis="y1",
                    showlegend=False,
                )
            )
    TempCol = {
        "TotalValues": {
            "color": "tomato",
            "fill": "tozeroy",
            "mode": "lines",
            "name": "TotalValues",
        },
        "AvableCash": {
            "color": "green",
            "fill": "tozeroy",
            "mode": "lines",
            "name": "AvableCash",
        },
        "winValue": {
            "color": "#fff",
            "name": "startCash",
            "fill": None,
            "mode": "lines",
        },
    }
    for col in TempCol:
        if col in cols:
            ColDic = TempCol[col]
            fig.add_trace(
                go.Scatter(
                    x=df["date"],
                    y=df[col],
                    marker=dict(color=ColDic["color"], size=10),
                    name=col,
                    fill=ColDic["fill"],
                    mode=ColDic["mode"],
                    yaxis="y6",
                    showlegend=False,
                )
            )

    domainL = {
        "y6": [0, 0.05],
        "y5": [0.05, 0.1],
        "y4": [0.1, 0.2],
        "y3": [0.2, 0.3],
        "y2": [0.3, 0.4],
        "y1": [0.4, 1],
    }
    if "zero" in cols:
        for r in range(len(domainL)):  # 添加0轴
            a = r + 1
            x = "y" + str(a)
            fig.add_trace(
                go.Scatter(
                    x=df["date"],
                    y=df["zero"],
                    marker=dict(color="black"),
                    name="zero",
                    text=df.loc[:, "date"],
                    mode="lines",
                    line=dict(width=1, dash="dot"),
                    yaxis=x,
                    showlegend=False,
                )
            )

    fig.update_layout(
        xaxis_rangeslider_visible=False,
        autosize=True,
        plot_bgcolor="#fff",
        showlegend=True,
        legend=dict(
            orientation="h",
            yanchor="bottom",
            y=0.97,
            xanchor="left",
            x=0.01,
            font=dict(
                size=9,
            ),
        ),
        modebar=dict(orientation="h"),
        spikedistance=-1,
        title=dict(
            font=dict(
                size=15,
            ),
        ),
        hovermode="x",
        margin=dict(l=10, r=10, t=20, b=10),
        xaxis=dict(
            gridcolor="rgb(240,240,240)",
            showspikes=True,
            spikemode="across+toaxis",
            spikesnap="cursor",
            spikedash="dot",
            autorange=True,
            showticklabels=False,
            gridwidth=1,
            scaleanchor="x",
            tickmode="array",
            type="category",
            # type="date",
            showline=False,
        ),
        yaxis1=dict(
            domain=domainL["y1"],
            gridcolor="rgb(240,240,240)",
            tickfont=dict(color="#C0C0C0"),
            ticklabelposition="inside top",
            anchor="x",
            mirror=True,
            gridwidth=1,
            type="linear",
            range=[df.low.min() * 0.9, df.high.max() * 1.1],
        ),
        yaxis2=dict(
            domain=domainL["y2"],
            gridcolor="rgb(240,240,240)",
            tickfont=dict(color="#C0C0C0"),
            ticklabelposition="inside top",
            anchor="x",
            mirror=True,
            gridwidth=1,
            type="linear",
        ),
        yaxis3=dict(
            domain=domainL["y3"],
            gridcolor="rgb(240,240,240)",
            tickfont=dict(color="#C0C0C0"),
            ticklabelposition="inside top",
            anchor="x",
            mirror=True,
            gridwidth=1,
            type="linear",
        ),
        yaxis4=dict(
            domain=domainL["y4"],
            gridcolor="rgb(240,240,240)",
            tickfont=dict(color="#C0C0C0"),
            ticklabelposition="inside top",
            anchor="x",
            mirror=True,
            gridwidth=1,
            type="linear",
        ),
        yaxis5=dict(
            domain=domainL["y5"],
            gridcolor="rgb(240,240,240)",
            tickfont=dict(color="#C0C0C0"),
            ticklabelposition="inside top",
            anchor="x",
            mirror=True,
            gridwidth=1,
            type="linear",
        ),
        yaxis6=dict(
            domain=domainL["y6"],
            gridcolor="rgb(240,240,240)",
            tickfont=dict(color="#C0C0C0"),
            ticklabelposition="inside top",
            anchor="x",
            mirror=True,
            gridwidth=1,
            type="linear",
        ),
    )
    if save_info != []:
        fig.write_html(
            "htmls/{}_{}_{}.html".format(save_info[0], save_info[1], save_info[2])
        )
        # fig.write_html("htmls/{}.html".format(save_info[0]))
    return fig